<?php
define("MAX_SIZE","10000");
$valid_formats = array("jpg","png","gif","bmp","jpeg");
try{
	$name = $_FILES["newImage"]["name"];
	$size = $_FILES["newImage"]["size"];
	$imgType = $_FILES["newImage"]["type"];
	$playerid = (isset($_POST["playerid"]) && trim($_POST["playerid"]) != "")?$_POST["playerid"]:$_SESSION["me"]->playerid;
	 						
	if(strlen($name)){
		list($txt,$ext) = explode(".", $name);
		$ext = strtolower($ext);
			
		if(in_array($ext,$valid_formats)){
			if($size < MAX_SIZE*1024){
				$uploadedfile = $_FILES["newImage"]["tmp_name"];
				if($ext == "jpg" || $ext == "jpeg"){
					$src = imagecreatefromjpeg($uploadedfile);
				}
				else if($ext == "png"){
					$src = imagecreatefrompng($uploadedfile);
				}
				else{
					$src = imagecreatefromgif($uploadedfile);
				}
					
				list($width,$height)=getimagesize($uploadedfile);
					
				$newwidth = 600;
				$newheight = $height*($newwidth/$width);
				$tmp = imagecreatetruecolor($newwidth,$newheight);
					
				$newwidth1 = 200;
				$newheight1 = $height*($newwidth1/$width);
				$tmp1 = imagecreatetruecolor($newwidth1,$newheight1);
					
				$newwidth2 = 75;
				$newheight2 = ($height/$width)*$newwidth2;
				$tmp2 = imagecreatetruecolor($newwidth2,$newheight2);
					
					
				imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
					
				imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
					
				imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$newheight2,$width,$height);
					
				$filename = "tmp/".$_SESSION["me"]->playerid."_".$name;
				$filename1 = "tmp/med_".$_SESSION["me"]->playerid."_".$name;
				$filename2 = "tmp/thumb_".$_SESSION["me"]->playerid."_".$name;
					
				imagejpeg($tmp,$filename,100);
				imagejpeg($tmp1,$filename1,100);
				imagejpeg($tmp2,$filename2,100);
					
				$imageData = file_get_contents($filename);
				$imageDataM = file_get_contents($filename1);
				$imageDataT = file_get_contents($filename2);
				$photoId = $this->model->addPlayerPhoto(null,$imageData,$imageDataM,$imageDataT,$imgType,$size,$name,$ext,$playerid,false);
					
					
				imagedestroy($src);
				imagedestroy($tmp);
				imagedestroy($tmp1);
				imagedestroy($tmp2);
				unlink($filename);
				unlink($filename1);
				unlink($filename2);
					
				$jsonOutput = "{\"message\":\"suceeded\"}";
			}
			else{
				$jsonOutput = "{\"message\":\"Size exeeded.\"}";
			}
		}
		else{
			$jsonOutput = "{\"message\":\"Error: Unkown image extension.\"}";
		}
	}
	else{
		$jsonOutput = "{\"message\":\"Error: No image selected.\"}";
	}
}
catch(Exception $e){
	$jsonOutput = sprintf("{\"message\":\"error: %s\"}",$e->getMessage());				
}
?>